#include "Server.hpp"

int Server::SocketInit(const char *ip_addr, int port)
{
	int s_s;
	struct sockaddr_in sockaddr_server;

	s_s = socket(AF_INET, SOCK_STREAM, 0);
	if(s_s < 0)
	{
		perror("SOCKET: ");
		return -1;
	}

	memset(&sockaddr_server, 0, sizeof(sockaddr_server));

	sockaddr_server.sin_port = htons(port);
	sockaddr_server.sin_family = AF_INET;
	sockaddr_server.sin_addr.s_addr = htonl(inet_addr(ip_addr));
	int err = bind(s_s, (struct sockaddr*)(&sockaddr_server), sizeof(sockaddr_server));
	if(err < 0)
	{
		perror("BIND: ");
		return err;
	}

	err = listen(s_s, 5);
	if (err < 0)
	{
		perror("LISTEN: ");
		return err;
	}
	return s_s;	
}

Server::Server(std::string n, const char *ip_addr, int port)
{
	name = n;
	clients_num = 0;
	fd = SocketInit(ip_addr, port);
	if(fd < 0)
	{
		//ERROR PROCESS
	}
}

void Server::start()
{
    ev_loop(loop, 0);
}

void Server::delConn(int fd)
{
	clients_num--;
	delete ConnManager[fd];
	ConnManager[fd] = NULL;
	ConnManager.erase(fd);
}

int Server::getClientsNum()
{
	return clients_num;
}

std::string Server::getName() const
{
	return name;
}

Server::~Server()
{
	for (std::map<int, Connection *>::iterator iter=ConnManager.begin(); iter!=ConnManager.end(); ++iter)
	{
		close(iter->first);
		delete ConnManager[iter->first];
	}
	ConnManager.clear();
}




